package com.haust.service.impl;

import com.haust.feign.CartFeign;
import com.haust.feign.ItemFeign;
import com.haust.mapper.TbOrderItemMapper;
import com.haust.mapper.TbOrderMapper;
import com.haust.mapper.TbOrderShippingMapper;
import com.haust.pojo.TbOrder;
import com.haust.pojo.TbOrderItem;
import com.haust.pojo.TbOrderShipping;
import com.haust.rabbit.message.dto.HaustCreateOrderMessageBody;
import com.haust.service.CreateOrderService;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CreateOrderServiceImpl implements CreateOrderService {
    @Autowired
    private TbOrderMapper orderMapper;

    @Autowired
    private TbOrderItemMapper orderItemMapper;

    @Autowired
    private TbOrderShippingMapper orderShippingMapper;

    @Autowired
    private ItemFeign itemFeign;

    @Autowired
    private CartFeign cartFeign;

    /**
     * 0、开启分布式事务
     * 1、创建订单，物流，订单数据项数据
     * 2、修改库存中的商品的库存
     * 3、修改redis中购物车数据
     * 4、提交或者回滚数据
     *
     * @param messageBody
     */
    @Override
    @LcnTransaction
    @Transactional
    public void createOrder(HaustCreateOrderMessageBody messageBody) {
        TbOrder tbOrder = messageBody.getTbOrder();
        List<TbOrderItem> tbOrderItems = messageBody.getTbOrderItem();
        TbOrderShipping tbOrderShipping = messageBody.getTbOrderShipping();

        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        //1、创建订单，物流，订单数据项数据
        orderMapper.insert(tbOrder);
        orderShippingMapper.insert(tbOrderShipping);
        for (TbOrderItem orderItem : tbOrderItems) {
            orderItemMapper.insert(orderItem);

            //给远程调用修改商品库存，准备参数
            HashMap<String, Object> map = new HashMap<>();
            map.put("itemId", orderItem.getItemId());
            map.put("num", orderItem.getNum());
            map.put("updated", tbOrder.getCreateTime().getTime());
            maps.add(map);
        }
        //2、使用OpenFeign进行远程调用更新商品库存
        itemFeign.updateItemNum4CreateOrder(maps);

        //3、远程调用购物车的清空
        cartFeign.clearCart4CreateOrder(maps, tbOrder.getUserId(),messageBody.getToken());

    }
}
